#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "driver/uart.h"
#include "string.h"
#include "driver/gpio.h"
#include "soc/uart_struct.h"
#include "serial.h"
#include "nvs_para.h"



#define RX_BUF_SIZE 512


static const char *TAG = "serial";

#define SERIAL_TXD_PIN (5)
#define SERIAL_RXD_PIN (4)

// #define SERIAL_TXD_PIN (27)
// #define SERIAL_RXD_PIN (26)



static SemaphoreHandle_t  uart_mutex;



extern void finger_data_handle(uint8_t *data, uint16_t len);
extern void finger_data_cmd_handle(uint8_t *data, uint16_t len);
extern void send_data_serial0(uint8_t *data, uint16_t len);

static void serial_rx_task(void *arg)
{
  uint8_t *buf;
  uint16_t len = 0;
  buf = malloc(RX_BUF_SIZE);

  while (1)
  {
    xSemaphoreTake(uart_mutex, portMAX_DELAY);
    len = uart_read_bytes(UART_NUM_1, buf, RX_BUF_SIZE, pdMS_TO_TICKS(50));
    if (len > 0)
    {
      buf[len] = 0;
      finger_data_cmd_handle(buf, len); // Process the received data
      memset(buf, 0, len);  
    }
    xSemaphoreGive(uart_mutex);
    vTaskDelay(pdMS_TO_TICKS(10));
  }
  free(buf);
}


void send_data_serial(uint8_t *data, uint16_t len)
{
	uart_write_bytes(UART_NUM_1, (const char *)data, len);
}


void serial_init(void)
{
  uart_mutex = xSemaphoreCreateMutex();
  const uart_config_t uart_config = {
      .baud_rate = 57600,
      .data_bits = UART_DATA_8_BITS,
      .parity = UART_PARITY_DISABLE,
      .stop_bits = UART_STOP_BITS_1,
      .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
  };

  uart_param_config(UART_NUM_1, &uart_config);
  uart_set_pin(UART_NUM_1, SERIAL_TXD_PIN, SERIAL_RXD_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
  uart_driver_install(UART_NUM_1, RX_BUF_SIZE * 2, 0, 0, NULL, 0);

  ESP_LOGI(TAG,"serial init");
  xTaskCreate(serial_rx_task, "serial_rx_task", 2024, NULL, 5, NULL);
}
